package com.mediacloud.app.newsmodule.fragment.comment;


import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.eventTrack.DataCollectRequestButtonClickExpansion;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.assembly.views.XRefreashListView;
import com.mediacloud.app.assembly.views.XRefreashListView.IXListViewListener;
import com.mediacloud.app.model.CommentCommitEvent;
import com.mediacloud.app.model.CommentCommitPushEvent;
import com.mediacloud.app.model.OnCommentUpdate;
import com.mediacloud.app.model.component.ComponentItem;
import com.mediacloud.app.model.fragment.BaseFragment;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.adaptor.comment.CommentReplyListener;
import com.mediacloud.app.newsmodule.adaptor.comment.NewsCommentItemAdaptor;
import com.mediacloud.app.newsmodule.adaptor.comment.x.XCommentActivity;
import com.mediacloud.app.newsmodule.datacollect.IButtonClickComment;
import com.mediacloud.app.newsmodule.model.CommentListDataReciver;
import com.mediacloud.app.newsmodule.model.NewsCommentItem;
import com.mediacloud.app.newsmodule.model.ReplyCommentItem;
import com.mediacloud.app.newsmodule.utils.CommentListDataInvoker;
import com.mediacloud.app.newsmodule.utils.CommentPopFactroy;
import com.mediacloud.app.newsmodule.view.CommentDialog;
import com.mediacloud.app.reslib.config.NewsDetailStyleConfig;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.user.model.UserInfo;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

//微直播那里还在用。特殊布局不好操作先就要用这个嵌套的方式
//自媒体列表也在用 。他的adapter不一样
public class NewsCommentFragment extends BaseFragment implements IXListViewListener, IButtonClickComment {

    protected View mCommentListView;
    protected TextView letmeSay, emptyTipsText;
    public NewsCommentItemAdaptor newsCommentItemAdaptor;
    //    protected CommentInputView commentInputView;
    protected View mEmptyContent;
    protected CommentListDataInvoker commentListInvoker;
    protected View lemesaylinly;
    protected ImageView letmeSaybnt;
    public ArticleItem articleItem;
    protected int page = 1;
    protected CommentListCallBack commentListCallBack;
    ShareViewHolder mShareViewHolder;

    String shareUrl = null;

//    CommentPopupWindow commentDialogFram;
    View xdebi;
    public boolean isSpider = false;
    private ComponentItem componentItem;
    private int type = 1;

    @Override
    public int getLayoutResID() {
        return R.layout.aappfactory_fragment_newscomment;
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    public void setAdapter() {
        newsCommentItemAdaptor = new NewsCommentItemAdaptor(getActivity());
        newsCommentItemAdaptor.isSpider = isSpider;
        newsCommentItemAdaptor.type = this.type;
        Log.i(TAG, "setAdapter componentItem is null ?  " + (componentItem == null));
        if (componentItem != null) {
            newsCommentItemAdaptor.show_type = componentItem.type;
            newsCommentItemAdaptor.detailComponentType = componentItem.getWidget();
        }
    }

    public void setMicroLiveNeeds() {

    }

    public void setMicroCommentNumbers(int total) {
    }

    @Override
    public void initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        boolean tag = getFragmentArguments().getBoolean("tag", false);
        boolean appfac = getFragmentArguments().getBoolean("appfac", false);
        articleItem = getFragmentArguments().getParcelable("data");
        isSpider = getFragmentArguments().getBoolean("isSpider", false);
        componentItem = getFragmentArguments().getParcelable("componentItem");
        type = getFragmentArguments().getInt("type");
        shareUrl = articleItem.getUrl();
        setAdapter();
        newsCommentItemAdaptor.mShareUrl = shareUrl;
        newsCommentItemAdaptor.newsTitle = articleItem.getTitle();
        newsCommentItemAdaptor.articleId =""+articleItem.getId();
        xdebi = Utility.findViewById(mRootView, R.id.xdebi);
        if (appfac)
            xdebi.setVisibility(View.GONE);
        letmeSaybnt = Utility.findViewById(mRootView, R.id.letmeSaybtn);
        letmeSaybnt.setVisibility(tag ? View.GONE : View.VISIBLE);
        letmeSaybnt.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                gotoCommentActivity();
            }
        });
        mShareViewHolder = new ShareViewHolder(mRootView);
        newsCommentItemAdaptor.setShareViewHolder(mShareViewHolder);
        emptyTipsText = Utility.findViewById(mRootView, R.id.emptyTipsText);
        mEmptyContent = Utility.findViewById(mRootView, R.id.mEmptyContent);
        mCommentListView = Utility.findViewById(mRootView, R.id.mCommentListView);
        Utility.invokeMethod(mCommentListView, "setAdapter", new Object[]{newsCommentItemAdaptor}, new Class[]{ListAdapter.class});
//        commentDialogFram = new CommentPopupWindow(getActivity());
//        commentDialogFram.setOnCommentListener(new CommentPopupWindow.OnCommentListener() {
//            @Override
//            public void onComment(@NonNull String content, String beReplayUserName, String beReplayUserId) {
//                collectComment(content, beReplayUserName, beReplayUserId);
//            }
//        });
//        commentDialogFram.type = type;
//        commentDialogFram.isSpider = this.isSpider;
//        commentDialogFram.access_token = getFragmentArguments().getString("access_token", null);
//        commentDialogFram.setAnonymousView();
        CommentDialog.Companion.startActivity(getActivity(),articleItem,type,getFragmentArguments().getString("access_token", ""),isSpider);
        loadingView = Utility.findViewById(mRootView, R.id.mLoadingView);
        initStateView();
        loadingView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TYPE_LOADING.equals(currentState)) {
                    showStateView(TYPE_LOADING, false);
                    onRefresh();
                }
            }
        });
        letmeSay = Utility.findViewById(mRootView, R.id.letmeSay);
        lemesaylinly = Utility.findViewById(mRootView, R.id.lemesaylinly);
        try {
            if (AppFactoryGlobalConfig.getAppServerConfigInfo(getContext()).getNewsDetailConfig()
                    .getLinkedHashSet().contains(NewsDetailStyleConfig.COMMENT_BOX)!=true){
                lemesaylinly.setVisibility(View.GONE);
            }else{
                lemesaylinly.setVisibility(View.VISIBLE);
            }

        }catch (Exception e){

        }
        if (mCommentListView instanceof XRefreashListView) {
            XRefreashListView mCommentListView = (XRefreashListView) this.mCommentListView;
            mCommentListView.setPullRefreshEnable(true);
            mCommentListView.setPullLoadEnable(true);
            mCommentListView.setXListViewListener(this);
        }

        mCommentListView.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                hideInputComment();
                return false;
            }
        });
        mEmptyContent.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                hideInputComment();
                return false;
            }
        });

        lemesaylinly.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.w(TAG, "let me say");

//                commentDialogFram.isReply = false;
//                commentDialogFram.show(getActivity().getWindow().getDecorView());
                CommentDialog.Companion.startActivity(getActivity(),articleItem,type,getFragmentArguments().getString("access_token", ""),false);

            }
        });

        mEmptyContent.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                onRefresh();
            }
        });
//        commentDialogFram.articleItem = articleItem;
        CommentPopFactroy.articleItem = articleItem;
//        commentDialogFram.commentListener = new CommentPopupWindow.SubmitCommentListener() {
//
//            @Override
//            public void success() {
//                if (getActivity()==null||requireActivity().isFinishing()||requireActivity().isDestroyed()){
//                    return;
//                }
//                hideInputComment();
//                onRefresh();
//            }
//
//            @Override
//            public void failed() {
//
//            }
//        };
        newsCommentItemAdaptor.setCommentReplyListener(new CommentReplyListener() {
            @Override
            public void onCommentReply(NewsCommentItem item) {
//                commentDialogFram.isReply = true;
//                commentDialogFram.setReplyData(item);
//                commentDialogFram.show(mRootView);
                CommentDialog.Companion.startActivity(getActivity(), articleItem,type,getFragmentArguments().getString("access_token", ""),true,true,item);
            }

            @Override
            public void onCommentReply(ReplyCommentItem item) {
//                commentDialogFram.isReply = true;
//                commentDialogFram.setReplyData(item);
//                commentDialogFram.show(mRootView);
                CommentDialog.Companion.startActivity(getActivity(), articleItem,type,getFragmentArguments().getString("access_token", ""),true,true,item);

            }
        });
        setMicroLiveNeeds();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    private void commentCommitPush(CommentCommitPushEvent data) {
        collectComment(data.getContent(), data.getBeReplayUserName(), data.getBeReplayUserId());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    private void commentCommit(CommentCommitEvent data) {
        if(data.isSuccess()){
            if (getActivity()==null||requireActivity().isFinishing()||requireActivity().isDestroyed()){
                return;
            }
            hideInputComment();
            onRefresh();
        }
    }

    @Override
    protected void initOther() {
        commentListCallBack = new CommentListCallBack();
        commentListInvoker = new CommentListDataInvoker(commentListCallBack);
        onRefresh();
    }

    protected void hideInputComment() {
        lemesaylinly.setVisibility(View.VISIBLE);
        letmeSay.setVisibility(View.VISIBLE);
        boolean tag = getFragmentArguments().getBoolean("tag", false);
        letmeSaybnt.setVisibility(tag ? View.GONE : View.VISIBLE);
//        commentDialogFram.dismiss();
    }

    protected void getNewsComment() {
        if (mCommentListView instanceof XRefreashListView) {
            XRefreashListView mCommentListView = (XRefreashListView) this.mCommentListView;
            mCommentListView.setRefreshTime(null);
        }
        if (articleItem != null) {
            if (isSpider) {
                commentListInvoker.getCommunityCommentList(String.valueOf(articleItem.getId()), page);
            } else {
                UserInfo userInfo = UserInfo.getUserInfo(getContext());
                commentListInvoker.getCommentList(type, String.valueOf(articleItem.getId()), page, userInfo.getUserid());
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onVideoPause(OnCommentUpdate commentUpdate) {
        onRefresh();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        if (commentListInvoker != null)
            commentListInvoker.destory();
//        if (commentDialogFram != null) {
//            commentDialogFram.dismiss();
//            commentDialogFram.destory();
//            commentDialogFram = null;
//        }
    }

    @Override
    public void collectComment(@NonNull String content, String beReplayUserName, String beReplayUserId) {
        if (getActivity() == null) {
            Log.e(TAG, "activity is null failed collectComment");
            return;
        }
        UserInfo userInfo = UserInfo.getUserInfo(getActivity());
        if (!userInfo.isLogin()) {
            Log.e(TAG, "user is not login why collect comment!");
            return;
        }
        DataCollectRequestButtonClickExpansion.operateComment(
                getActivity().getClass().getName(),
                DataCollectRequestButtonClickExpansion.POSITIVE_ACTION,
                articleItem.getCatalogId() + "",
                articleItem.getId() + "",
                content,
                userInfo.getNickname(),
                beReplayUserName,
                userInfo.getUserid(),
                beReplayUserId);
    }

    public class CommentListCallBack implements DataInvokeCallBack<CommentListDataReciver> {

        @Override
        public void success(CommentListDataReciver data) {
            if (getActivity()==null||requireActivity().isFinishing()||requireActivity().isDestroyed()){
                return;
            }
            if (mCommentListView instanceof XRefreashListView) {
                XRefreashListView mCommentListView = (XRefreashListView) NewsCommentFragment.this.mCommentListView;
                mCommentListView.stopLoadMore();
                mCommentListView.stopRefresh();
                mCommentListView.setPullRefreshEnable(true);
                mCommentListView.setPullLoadEnable(data.more);
            }
            if (data.state) {
                setMicroCommentNumbers(data.total);
            }
            newsCommentItemAdaptor.articleItem = articleItem;
            if (data.state && data.commentList != null /*&& data.commentList.size() > 0*/) {
                if (page == 1) {

                    newsCommentItemAdaptor.setListContentData(data.commentList);
                } else {
                    if (newsCommentItemAdaptor.getListContentData() == null) {
                        newsCommentItemAdaptor.setListContentData(data.commentList);
                    } else
                        newsCommentItemAdaptor.getListContentData().addAll(data.commentList);
                }
                newsCommentItemAdaptor.notifyDataSetChanged();
//                if (data.page == data.pages) {
//                    mCommentListView.setPullLoadEnable(false);
//                } else {
//                    mCommentListView.setPullLoadEnable(true);
//                }
                if (newsCommentItemAdaptor.getCount() > 0) {
//                    mEmptyContent.setVisibility(View.GONE);
                    closeStateView();
                } else {
//                    mEmptyContent.setVisibility(View.VISIBLE);
                    emptyTipsText.setText(R.string.empty_comment);
                    showStateView(TYPE_NO_CONTENT, false);
                    if (mCommentListView instanceof XRefreashListView) {
                        XRefreashListView mCommentListView = (XRefreashListView) NewsCommentFragment.this.mCommentListView;
                        mCommentListView.setPullLoadEnable(false);
                    }
                }
            } else if (newsCommentItemAdaptor.getListContentData() == null || newsCommentItemAdaptor.getListContentData().size() == 0) {
                fault(null);
            }
        }

        @Override
        public void fault(Object data) {
            if (getActivity()==null||requireActivity().isFinishing()||requireActivity().isDestroyed()){
                return;
            }
            page--;
//            mEmptyContent.setVisibility(View.VISIBLE);
            if (data == null) {
                showStateView(TYPE_NO_CONTENT, false);
            } else {
                showStateView(TYPE_NET_NOT_GIVE_FORCE, false);
            }
            emptyTipsText.setText(R.string.empty_comment);
            if (mCommentListView instanceof XRefreashListView) {
                XRefreashListView mCommentListView = (XRefreashListView) NewsCommentFragment.this.mCommentListView;
                mCommentListView.stopLoadMore();
                mCommentListView.stopRefresh();
                mCommentListView.setPullLoadEnable(false);
                mCommentListView.setPullRefreshEnable(true);
            }
        }

    }

    @Override
    public void onRefresh() {
        page = 1;
        if (mCommentListView instanceof XRefreashListView) {
            XRefreashListView mCommentListView = (XRefreashListView) NewsCommentFragment.this.mCommentListView;
            mCommentListView.setPullLoadEnable(false);
        }
        emptyTipsText.setText("");
        getNewsComment();
    }

    @Override
    public void onLoadMore() {
        page++;
        if (mCommentListView instanceof XRefreashListView) {
            XRefreashListView mCommentListView = (XRefreashListView) NewsCommentFragment.this.mCommentListView;
            mCommentListView.setPullRefreshEnable(false);
        }
        emptyTipsText.setText("");
        getNewsComment();
    }

    public void gotoCommentActivity() {
        Intent intent = new Intent();
        intent.putExtra("data", articleItem);
        intent.setClass(this.getActivity(), XCommentActivity.class);
        startActivity(intent);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putParcelable("data", articleItem);
        boolean tag = getFragmentArguments().getBoolean("tag", false);
        outState.putBoolean("tag", tag);
        super.onSaveInstanceState(outState);
    }

}